<?php

/**
 *
 */
class App_Plugins_Admin_Auth extends Zend_Controller_Plugin_Abstract
{
	/**
	 * 
	 * @var Zend_Controller_Plugin_Abstract
	 */
	protected $_request;
	
	/**
	 * 
	 * @var Zend_Config_Ini
	 */
	protected $_config;

	/**
	 * 
	 * @var array
	 */
	protected $_noAuth = array(
		'module' 		=> 'admin', 
		'controller' 	=> 'auth', 
		'action' 		=> 'index'
	);

	/**
	 * 
	 * @var Zend_Auth
	 */
	protected $_auth;

	/**
	 * (non-PHPdoc)
	 * @see Zend_Controller_Plugin_Abstract::dispatchLoopStartup()
	 */
	public function dispatchLoopStartup ( Zend_Controller_Request_Abstract $request )
	{
		$this->_request = $request;
		$this->_auth 	= Zend_Auth::getInstance();
		$this->_config 	= Zend_Registry::get('config');
		
		$storage = new Zend_Auth_Storage_Session( 'Auth_' . ucfirst($this->_config->geral->appid) );
		$this->_auth->setStorage( $storage );
		
		$this->_hasCookie();
		
		if ( !$this->_auth->hasIdentity() && 'auth' !== $this->_request->getControllerName() ) 
			$this->_routeNoAuth();
			
		return true;
	}
	
	/**
	 * 
	 * @access protected
	 * @return void
	 */
	protected function _hasCookie ()
	{
		if ( !$this->_auth->hasIdentity() && 'auth' !== $this->_request->getControllerName() ) {
			
			//Nome do cookie
			$name = 'auth_admin_' . $this->_config->geral->appid;
			
			if ( isset($_COOKIE[$name]) ) {
				
				$mapper = new Admin_Model_Mapper_Auth();
				
				$row = $mapper->fetchRowCookie( $_COOKIE[$name] );
				
				if ( !empty($row) )
					$this->_auth->getStorage()->write( $row );
				else 
					$this->_routeNoAuth();
					
			} else $this->_routeNoAuth();
			
		}
	}

	/**
	 * 
	 * @access protected
	 * @return void
	 */
	protected function _routeNoAuth ()
	{
		$this->_auth->clearIdentity();
		
		$session = new Zend_Session_Namespace( $this->_config->geral->appid );
		
		$session->triedroute = $this->_request->getRequestUri();
		
		$this->_setRoute( $this->_noAuth );
	}

	/**
	 * 
	 * @access 	protected
	 * @param 	array $route
	 * @return 	void
	 */
	protected function _setRoute ( array $route )
	{
		$this->_request->setControllerName( $route['controller'] );
		$this->_request->setModuleName( $route['module'] );
		$this->_request->setActionName( $route['action'] );
	}
}